package com.vilen.weixin.web.filter;

import com.vilen.basic.model.User;
import com.vilen.basic.service.IUserService;
import com.vilen.weixin.model.WeixinFinalValue;
import com.vilen.weixin.service.IWUserService;
import com.vilen.weixin.web.servlet.BeanFactoryContext;
import com.vilen.weixin.web.servlet.WeixinContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2016/2/19.
 */
public class WeixinAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User tu = (User) request.getSession().getAttribute("user");
        System.out.println(tu+"------");
        if(tu == null) {
            //才做授权
            String agent = request.getHeader("User-Agent");

            //微信客户端
            if(agent!=null && agent.toLowerCase().indexOf("micromessenger")>=0) {
                System.out.println(agent);
                String code = servletRequest.getParameter("code");
                String state = servletRequest.getParameter("state");
                System.out.println("code"+code+","+"state"+state);
                if(code!=null && state!=null && state.equals("1")){
                    //通过code获取openid来进行授权
                    IWUserService wUserService =(IWUserService) BeanFactoryContext.getService("wUserService");
                    String openid = wUserService.queryOpenidByCode(code);
                    if(openid!=null) {
                        //授权成功
                        IUserService userService = (IUserService) BeanFactoryContext.getService("userService");
                        User u = userService.loadByOpenid(openid);
                        if(u==null) {
                            //用户对象不存在  关注的时候系统没开机
                            u = wUserService.queryByOpenid(openid).getUser();
                            userService.add(u);
                        }else {
                            if(u.getStatus() ==0) {
                                u.setStatus(1);
                                userService.update(u);
                            }
                        }
                        request.getSession().setAttribute("user",u);
                    }
                }else{
                    String path = request.getRequestURL().toString();
                    String query = request.getQueryString();
                    if(query!=null) {
                        path = path +"?"+ query;
                    }
                    System.out.println(path);
                    path = URLEncoder.encode(path,"UTF-8");
                    String url = WeixinFinalValue.AUTH_URL;
                    url = url.replace("APPID", WeixinContext.getInstance().getAppId())
                            .replace("REDIRECT_URI", path)
                            //用户没有关注的时候 会弹出验证
                            //.replace("SCOPE","snsapi_userinfo")
                            .replace("SCOPE","snsapi_base")
                            .replace("STATE","1");
                    response.sendRedirect(url);
                    System.out.println(url);
                    return;
                }

            }
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
